package org.casscommunity.sights.client.widget.editor;

import com.google.gwt.editor.client.EditorDelegate;
import com.google.gwt.editor.client.HasEditorDelegate;
import com.google.gwt.editor.client.adapters.TakesValueEditor;
import com.google.gwt.user.client.TakesValue;

public class ValueEditorWithDelegate<T> extends TakesValueEditor<T> implements HasEditorDelegate<T> {

	public static <T> ValueEditorWithDelegate<T> of(TakesValue<T> valueBox) {
		return new ValueEditorWithDelegate<T>(valueBox);
	}

	private EditorDelegate<T> delegate;
	private final TakesValue<T> peer;
	private T value;
	
	protected ValueEditorWithDelegate(TakesValue<T> valueBox) {
		super(valueBox);
		peer = valueBox;
	}
	
	@SuppressWarnings("unchecked")
	public void setDelegate(EditorDelegate<T> delegate) {
		if (peer instanceof HasEditorDelegate) {
			((HasEditorDelegate<T>) peer).setDelegate(delegate);
		}
		this.delegate = delegate;
	}
	
	public void setValue(T value) {
		peer.setValue(this.value = value);
	}
	
	@Override
	public T getValue() {
		value = peer.getValue();
		return value;
	}
	
	public String getBeanPath() {
		return delegate.getPath();
	}

}
